const express = require('express')
const { v4 } = require('uuid')
const GlobalUtils = require('../../tools/GlobalUtils')

// 用户数据表
const userTable = require('../../db/user/userTable')
const userDetailTable = require('../../db/user/userDetailTable')

const registerApp = express()

// 注册服务
registerApp.post('/', async (req, res) => {
  // 生成唯一密钥
  let key = v4().replaceAll('-', '')
  // 加密
  let { userName, password, avatar } = req.body

  if (!avatar) {
    avatar = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
  }

  let newPassword = GlobalUtils.enCryptData(password, key, 'sha256')
  // 随机访问令牌
  let token = GlobalUtils.enCryptData(v4(), v4(), 'sha256')
  // 存储数据
  const user = await userTable.findOne({ userName })
  if (user) {
    return res.send({ status: 500, message: '用户名已存在！' })
  }

  try {
    // 数据库中没有用户 就可以添加新用户
    await userTable.create(
      {
        userName,
        password: newPassword,
        key,
        token,
        avatar,
        introduction: '',
        isAdmin: false,
        superAdmin: false,
        approved: true,
        freezed: false,
        createTime: new Date()
      }
    )

    // 更新用户详情表
    await userDetailTable.create({
      key,
      articles: [],
      comments: [],
      likes: [],
      attentions: [],
      fans: [],
      blackList: []
    })

    // 返回 token
    res.setHeader('Authorization', token)
    res.send({
      status: 200,
      message: '注册成功！'
    })
  } catch (e) {
    console.log(e);
    res.send({
      status: 500,
      message: '注册失败！'
    })
  }
  
})

module.exports = registerApp